 package com.ptr.ptrsystem.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ptr.ptrsystem.logica.LogicaPersona;
import com.ptr.controladores.conexionsqlserver;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.ptr.ptrsystem.bean.Persona;
import javax.servlet.http.HttpSession;
import javax.swing.JOptionPane;
/**
 *
 * @author pavel
 */
@WebServlet(name = "MantenimientoPersona", urlPatterns = {"/MantenimientoPersona"})
public class MantenimientoPersonaServlet extends HttpServlet {

    public MantenimientoPersonaServlet() {
    }
conexionsqlserver base=new conexionsqlserver();
Connection conn;
Statement st;
ResultSet rs;
ResultSet rs3=null;
String ubigeo=null;
//
String ubin=null;
String depa1;
String prov1;
String dist1;
String otr1;
//
String nomubin=null;
String ubigeodom=null;
String ubid=null;

String CUI_PERS=null;
String NRO_ACTA_PERS=null;String NRO_LIBRO_ACTA_NAC=null;
String PRIM_APE_PERS=null;String SEG_APE_PERS=null;
String APE_CASADA=null;String PRE_NOM_PERS=null;
String IDUBIGEO_DOMICI=null;String COD_DIR=null;
String DIR_PERS=null;String NRO_DIR=null;
String GEN_PERS=null;String FOTO_PERSONA=null;
String TELEF_1=null;String TELEF_2=null;
String EST_CIVIL_PERS=null;String COD_NACIONALIDAD=null;
String IDUBIGEO=null;String COD_ESTADO_PERS=null;
String COD_CARGO=null;
//ubigeo Nacimiento
String unac=null;String d1=null;
String p1=null;String di1=null;
String otro1=null;
//Ubigeo Domicilio
String d2=null;String p2=null;
String di2=null;String otr2=null;
//
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
//////////////////
                ubigeo=request.getParameter("ubigeonac");
                ubigeodom=request.getParameter("ubigeodom");
       if(ubigeo!=null)
        {
            try
            {
                base.conectar();
                conn=base.getconection();
                st=conn.createStatement();
                String query8="select * from TB_UBIGEO";
                query8=query8+" where idubigeo='"+ubigeo+"'";
                ResultSet rsn=st.executeQuery(query8);
                if(rsn.next())
                {
                    ubin=rsn.getString(1);
                    depa1=rsn.getString(2);
                    prov1=rsn.getString(3);
                    dist1=rsn.getString(4);
                    otr1=rsn.getString(5);
                    nomubin=rsn.getString(6)+" / "+rsn.getString(7)+" / "+rsn.getString(8)+" / "+rsn.getString(9);
                    out.println(rsn.getString(6)+" / "+rsn.getString(7)+" / "+rsn.getString(8)+" / "+rsn.getString(9));
                }else
                {
                    out.println("No existe el ubigeo selecccionado");
                }
            }
            catch(SQLException er)
            {
                er.printStackTrace();
            }
        }
       if(ubigeodom!=null)
        {
            try
            {
                base.conectar();
                conn=base.getconection();
                st=conn.createStatement();
                String query6="select * from TB_UBIGEO";
                query6=query6+" where idubigeo='"+ubigeodom+"'";
                ResultSet rsd=st.executeQuery(query6);
                if(rsd.next())
                {
                    ubid=rsd.getString(1);
                    out.println(rsd.getString(6)+" / "+rsd.getString(7)+" / "+rsd.getString(8)+" / "+rsd.getString(9));
                }else
                {
                    out.println("No existe el ubigeo selecccionado");
                }
            }
            catch(SQLException er)
            {
                er.printStackTrace();
            }
        }  
/////////////        
        
        
        CUI_PERS=request.getParameter("cui");
        NRO_ACTA_PERS=request.getParameter("nroacta");
        NRO_LIBRO_ACTA_NAC=request.getParameter("nrolibro");
        PRIM_APE_PERS=request.getParameter("pape");
        SEG_APE_PERS=request.getParameter("sape");
        APE_CASADA=request.getParameter("apecas");
        PRE_NOM_PERS=request.getParameter("pnom");
        COD_DIR=request.getParameter("cdir");
        DIR_PERS=request.getParameter("direccion");
        NRO_DIR=request.getParameter("nro");
        GEN_PERS=request.getParameter("genero");
        FOTO_PERSONA="NINGUNO";
        TELEF_1=request.getParameter("tel1");
        TELEF_2=request.getParameter("tel2");
        EST_CIVIL_PERS=request.getParameter("ecivil");
        COD_NACIONALIDAD=request.getParameter("nacio");
        COD_ESTADO_PERS=request.getParameter("tipoestadop");;
        COD_CARGO="00";
        
        ///Ubigeo Nacimiento
            d1=request.getParameter("Dep");
            p1=request.getParameter("Prov");
            di1=request.getParameter("Dist");
            otr1=request.getParameter("Otro");
        ///Ubigeo Domicilio
            d2=request.getParameter("Depd");
            p2=request.getParameter("Provd");
            di2=request.getParameter("Distd");
            otr2=request.getParameter("Otrod");
        //
        String b=request.getParameter("btn1");        
        if("guardapers".equals(b))
        {GuardaDatosPersona(request,response);}
        if("Busuario".equals(b))
        {BuscaPersona(request,response);}
        if("matrimonio".equals(b))
        {registromatrimonio(request, response);}
        if("defuncion".equals(b))
        {registrodefuncion(request, response);}
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(MantenimientoPersonaServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(MantenimientoPersonaServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void GuardaDatosPersona(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();              
        String ubinacimiento=d1+p1+di1+otr1;
        String ubigeodomicilio=d2+p2+di2+otr2;
        
        if((CUI_PERS.equals("null")) || (NRO_ACTA_PERS.equals("null"))){
            request.setAttribute("msj", "0");
            JOptionPane.showMessageDialog(null, "No debe ingresar valores nulos o vacios", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            request.getRequestDispatcher("/jsp/Nusuario.jsp").forward(request, response);
        }else{  
            LogicaPersona logpers=new LogicaPersona();
            boolean pers=logpers.InsertarPersona(CUI_PERS, NRO_ACTA_PERS, NRO_LIBRO_ACTA_NAC, PRIM_APE_PERS, 
                    SEG_APE_PERS, APE_CASADA, PRE_NOM_PERS, ubigeodomicilio, COD_DIR, DIR_PERS, NRO_DIR,
                    GEN_PERS, FOTO_PERSONA, TELEF_1, TELEF_2, EST_CIVIL_PERS, COD_NACIONALIDAD, ubinacimiento, COD_ESTADO_PERS, COD_CARGO);
                    if(pers)
                    {
                        request.setAttribute("CUI", CUI_PERS); 
                        request.setAttribute("NA",NRO_ACTA_PERS);
                        request.setAttribute("NL",NRO_LIBRO_ACTA_NAC);
                        request.setAttribute("PA",PRIM_APE_PERS);
                        request.setAttribute("SA",SEG_APE_PERS);
                        request.setAttribute("AC",APE_CASADA);
                        request.setAttribute("PN",PRE_NOM_PERS);
                        request.setAttribute("UD",IDUBIGEO_DOMICI);
                        try
                        {
                         base.conectar();
                         conn=base.getconection();
                         st=conn.createStatement();
                         String query1="select NOM_TIPO_DIR from TB_TIPO_DIRECCION";
                         query1=query1+" where COD_DIR='"+COD_DIR+"'";
                         rs=st.executeQuery(query1);
                         if(rs.next())
                         {
                            request.setAttribute("ndir", rs.getString(1));
                         }
                        }catch(SQLException a)
                        {System.out.println("Error al Buscar el tipo de direccion"+a.getMessage());}

                        request.setAttribute("DP",DIR_PERS);
                        request.setAttribute("ND",NRO_DIR);
                        request.setAttribute("G",GEN_PERS);
                        request.setAttribute("F",FOTO_PERSONA);
                        request.setAttribute("T1",TELEF_1);
                        request.setAttribute("T2",TELEF_2);
                        request.setAttribute("EC",EST_CIVIL_PERS);
                        request.setAttribute("CN",COD_NACIONALIDAD);
                        try
                        {
                            base.conectar();
                            conn=base.getconection();
                            st=conn.createStatement();
                            String query2="select NOM_NACIONALIDAD from TB_NACIONALIDAD";
                            query2=query2+" where COD_NACIONALIDAD='"+COD_NACIONALIDAD+"'";
                            rs=st.executeQuery(query2);
                            if(rs.next())
                            {
                            request.setAttribute("CNAC",rs.getString(1));
                            }
                        }
                        catch(SQLException cna)
                        {System.out.println("Error al Buscar el tipo de Nacionalidad"+cna.getMessage());}
                        request.setAttribute("U",IDUBIGEO);
                        //
                        try
                        {
                            base.conectar();
                            conn=base.getconection();
                            st=conn.createStatement();

                            String query3="select nom_ubigeo_dep,nom_ubigeo_prov,";
                            query3=query3+" nom_ubigeo_dist, nom_ubigeo_otro from TB_UBIGEO";
                            query3=query3 +" where idubigeo='"+IDUBIGEO+"'";
                            rs=st.executeQuery(query3);
                            if(rs.next())
                            {
                                unac=rs.getString(1)+" / "+rs.getString(2)+" / "+rs.getString(3)+" / "+rs.getString(4);                    
                                request.setAttribute("unaci", unac);
                            }
                        }catch(SQLException e)
                        {System.out.println("Error al buscar el ubigeo del domicilio"+e.getMessage());}
                        //
                        try
                        {
                            base.conectar();
                            conn=base.getconection();
                            st=conn.createStatement();
                            String query4="select NOM_ESTADO_PERS from TB_ESTADO_PERSONA";
                            query4=query4+" where COD_ESTADO_PERS='"+COD_ESTADO_PERS+"'";
                            rs=st.executeQuery(query4);
                            if(rs.next())
                            {request.setAttribute("CEP", rs.getString(1));}
                        }catch(SQLClientInfoException ep)
                        {System.out.println("Error al Buscar el tipo de Nacionalidad"+ep.getMessage());}
                        request.setAttribute("CC",COD_CARGO);
                        RegistrarNacimiento(request,response);
                    }
                    else
                    {
                        request.setAttribute("msj", "1");
                        getServletContext().getRequestDispatcher("/jsp/NNacimiento.jsp").forward(request, response);
                    }
    }
    }
    private void RegistrarNacimiento(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();  
        LogicaPersona logp=new LogicaPersona();
           HttpSession session = request.getSession();
           session.setAttribute("pers", CUI_PERS);
           
             request.setAttribute("cui", CUI_PERS);
             request.setAttribute("nroacta", NRO_ACTA_PERS);
             request.setAttribute("libro", NRO_LIBRO_ACTA_NAC);
             
             if(GEN_PERS.equals("M")){request.setAttribute("GEN", "MASCULINO");}
             else{if(GEN_PERS.equals("F")){request.setAttribute("GEN", "FEMENINO");}}
             /// ubigeo de Nacimiento
                    request.setAttribute("ubinac", ubin);
                    request.setAttribute("depa1", d1);
                    request.setAttribute("prov1", p1);
                    request.setAttribute("dist1", di1);
                    request.setAttribute("otr1", otr1);
             ////
             request.setAttribute("nomubin", nomubin);
           base.conectar();
           try
           {
               conn=base.getconection();
               st=conn.createStatement();
               String query2="SELECT PRIM_APE_PERS, SEG_APE_PERS, APE_CASADA, PRE_NOM_PERS FROM TB_PERSONA";
               query2=query2+" WHERE CUI_PERS='"+CUI_PERS+"'";
               rs=st.executeQuery(query2);
               while(rs.next())
               {
                   request.setAttribute("pa", rs.getString(1));
                   request.setAttribute("sa", rs.getString(2));
                   request.setAttribute("apca", rs.getString(3));
                   request.setAttribute("pnom", rs.getString(4));
               }
           }catch(SQLException e)
           {
               out.println("Problemas en la busqueda de Datos"+ e.getMessage());
           }
           getServletContext().getRequestDispatcher("/jsp/NNacimiento.jsp").forward(request, response);   
       }

    private void BuscaPersona(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();  
        base.conectar();
        try
        {
            conn=base.getconection();
            st=conn.createStatement();
            String sql="SELECT CUI_PERS, NRO_ACTA_PERS,";
            sql=sql+" NRO_LIBRO_ACTA_NAC,PRIM_APE_PERS,";
            sql=sql+" SEG_APE_PERS, APE_CASADA,";
            sql=sql+" PRE_NOM_PERS, IDUBIGEO,";
            sql=sql+" IDUBIGEO_DOMICI ";
            sql=sql+" FROM TB_PERSONA";
            sql=sql+" WHERE CUI_PERS='"+CUI_PERS+"' or NRO_ACTA_PERS='"+ NRO_ACTA_PERS+"'";
            ResultSet rs1=st.executeQuery(sql);
            if(rs1.next())
            {                
                request.setAttribute("cuin", rs1.getString(1));
                request.setAttribute("nron", rs1.getString(2));
                request.setAttribute("nroln", rs1.getString(3));
                request.setAttribute("ap1", rs1.getString(4));
                request.setAttribute("sapen", rs1.getString(5));
                request.setAttribute("capen", rs1.getString(6));
                request.setAttribute("pnomn", rs1.getString(7));
                request.setAttribute("ubinacn", rs1.getString(8));
                    try
                    {
                        base.conectar();
                        conn=base.getconection();
                        st=conn.createStatement();
                        String query5="select nom_ubigeo_dep, nom_ubigeo_prov,";
                        query5=query5+" nom_ubigeo_dist, nom_ubigeo_otro from TB_UBIGEO";
                        query5=query5+" WHERE idubigeo='"+rs1.getString(8)+"'";
                        ResultSet rs2=st.executeQuery(query5);
                        if(rs2.next())
                        {
                            request.setAttribute("dep1", rs2.getString(1));
                            request.setAttribute("prov1", rs2.getString(2));
                            request.setAttribute("dist1", rs2.getString(3));
                            request.setAttribute("otro1", rs2.getString(4));
                        }
                    }catch(SQLException ubi)
                    {
                        out.println("Error en ubicar el Ubigeo nacimiento: "+ubi.getMessage());
                    }
                request.setAttribute("ubidomn", rs1.getString(9));
                JOptionPane.showMessageDialog(null, "EL usuario ya se encuentra registrado","Informacion",JOptionPane.ERROR_MESSAGE);
                getServletContext().getRequestDispatcher("/jsp/Nusuario.jsp").forward(request, response);
            }else
            {
                JOptionPane.showMessageDialog(null, "EL usuario no se encuentra registrado","Informacion",JOptionPane.INFORMATION_MESSAGE);
                getServletContext().getRequestDispatcher("/jsp/Nusuario.jsp").forward(request, response);
            }
        }catch(SQLException usu)
        {
            out.println("Existe error en la busqueda de la Persona"+usu.getMessage());
        }
    }

    private void registromatrimonio(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();  
        try
        {
         base.conectar();
         conn=base.getconection();
         st=conn.createStatement();
         String query3="select CUI_PERS,NRO_ACTA_PERS,PRIM_APE_PERS,";
         query3=query3+" SEG_APE_PERS, APE_CASADA ,PRE_NOM_PERS from TB_PERSONA";
         query3=query3+" WHERE NRO_ACTA_PERS='"+NRO_ACTA_PERS+"'";
         rs=st.executeQuery(query3);
         if(rs.next())
         {
             out.println(rs.getString(1));
             out.println(rs.getString(2));
             out.println(rs.getString(3));
             out.println(rs.getString(4));
             out.println(rs.getString(5));
             out.println(rs.getString(6));
             out.println("Matrimonio");
         }
        }catch(SQLException mat)
        {
            out.println("Error en la busqueda de la Persona - Matrimonio: " + mat.getMessage());
        }
    }

    private void registrodefuncion(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter(); 

        try
        {
            base.conectar();
         conn=base.getconection();
         st=conn.createStatement();
         String query4="select CUI_PERS,NRO_ACTA_PERS,PRIM_APE_PERS,";
         query4=query4+" SEG_APE_PERS, APE_CASADA ,PRE_NOM_PERS from TB_PERSONA";
         query4=query4+" WHERE NRO_ACTA_PERS='"+NRO_ACTA_PERS+"'";
         rs=st.executeQuery(query4);
         if(rs.next())
         {
             out.println(rs.getString(1));
             out.println(rs.getString(2));
             out.println(rs.getString(3));
             out.println(rs.getString(4));
             out.println(rs.getString(5));
             out.println(rs.getString(6));
             out.println("Defuncion");
         }
        }catch(SQLException def)
        {
            out.println("Error en la busqueda de la Persona - Defuncion: " + def.getMessage());
        }
    }
    }